#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Node {
    int id;
    char name[20];
    int password;
    struct Node* next;
} Node;

Node* create_node(int id, const char* name, int password) {
    Node* new_node = (Node*)malloc(sizeof(Node));
    new_node->id = id;
    strcpy(new_node->name, name);
    new_node->password = password;
    new_node->next = new_node;
    return new_node;
}

Node* build_circular_list(int n) {
    Node *head = NULL, *prev = NULL;
    for (int i = 0; i < n; i++) {
        char input[50];
        scanf("%s", input);
        char* id_str = strtok(input, ",");
        char* name = strtok(NULL, ",");
        char* pwd_str = strtok(NULL, ",");
        int id = atoi(id_str);
        int password = atoi(pwd_str);
        Node* curr = create_node(id, name, password);
        if (head == NULL) {
            head = curr;
        } else {
            prev->next = curr;
            curr->next = head;
        }
        prev = curr;
    }
    return head;
}

void solve_josephus(Node* head, int initial_m) {
    Node *curr = head, *prev = NULL;
    int m = initial_m;
    while (curr->next != curr) {
        for (int i = 1; i < m; i++) {
            prev = curr;
            curr = curr->next;
        }
        printf("%d,%s,%d\n", curr->id, curr->name, curr->password);
        m = curr->password;
        prev->next = curr->next;
        free(curr);
        curr = prev->next;
    }
    printf("%d,%s,%d\n", curr->id, curr->name, curr->password);
    free(curr);
}

int main() {
    int n, m;
    scanf("%d", &n);
    Node* head = build_circular_list(n);
    scanf("%d", &m);
    solve_josephus(head, m);
    return 0;
}
